<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :disabled="readonly"
             :model="formData"
             :rules="formRules"
             class="full-form"
             label-width="100px"
             status-icon>

      <el-form-item label="应用名称：" prop="name">
        <el-input v-model="formData.name" :readonly="readonly" placeholder="请输入应用名称"/>
      </el-form-item>

      <el-form-item label="Identifier：" prop="bundle_id">
        <el-input v-model="formData.bundle_id" :readonly="readonly" placeholder="请输入Identifier"/>
      </el-form-item>

      <el-form-item label="应用类型：" prop="type">
        <el-radio-group v-model="formData.type" :disabled="readonly">
          <el-radio :value="0">Android</el-radio>
          <el-radio :value="1">iOS</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-if="formData.type === 1" label="TF测试地址：">
        <el-input v-model="formData.store_url" :autosize="{ minRows: 1}" :readonly="readonly" placeholder="请输入TF测试地址" type="textarea"/>
      </el-form-item>

      <el-form-item label="应用图标：" prop="icon_url">
        <el-input v-model="formData.icon_url" :autosize="{ minRows: 1}" :readonly="readonly" placeholder="请输入链接地址或点击下方进行上传" style="margin-bottom: 5px" type="textarea"/>
        <UploadImage v-model="formData.icon_url" :disabled="readonly" :show-delete="true" upload-path="app"/>
      </el-form-item>

      <el-form-item label="应用介绍：" prop="description">
        <el-input v-model="formData.description" :autosize="{ minRows: 2}" :readonly="readonly" placeholder="请输入应用介绍" type="textarea"/>
      </el-form-item>

      <el-form-item label="是否显示：">
        <el-switch v-model="formData.enabled"
                   :disabled="readonly"
                   active-text="启用"
                   inactive-text="禁用"
                   inline-prompt/>
      </el-form-item>
    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!readonly" v-permission="['user:certify:create', 'user:certify:update']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { UploadImage } from '@/components/upload';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { appInfo, appSaveOrUpdate, defAppInfo } from '@/api/api-app.ts';

defineOptions({name: 'app-info-form'})

const formRef = ref<FormInstance>();
const formLoading = ref(false);// 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

// 表单数据
const formData = ref({...defAppInfo});

// 表单验证规则
const formRules = reactive<FormRules>({
  type: [{required: true, message: '请选择 App 类型', trigger: 'blur'}],
  name: [{required: true, message: '请输入应用名称', trigger: 'blur'}],
  bundle_id: [{required: true, message: '请输入Identifier', trigger: 'blur'}],
  icon_url: [{required: true, message: '请上传应用图标', trigger: 'blur'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 是否新增 */
const isCreate = computed(() => {
  return dialogMode.value == 1 || formData.value.id <= 0;
});

/** 打开弹窗 */
const open = async (mode: number, id?: number) => {
  dialogMode.value = mode;
  dialogTitle.value = 'App应用';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();

  // 加载数据
  if (id) {
    formLoading.value = true
    try {
      // 加载用户数据
      const {data} = await appInfo(id)
      formData.value = data;
    } finally {
      formLoading.value = false
    }
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open})

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 提交数据
    appSaveOrUpdate(formData.value, isCreate.value).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())

  });
};

/** 重置表单 */
const handleFormReset = () => {
  // 重置表单数据
  formData.value = {...defAppInfo};
  formData.value.enabled = true;
  // 重置界面表单数据
  formRef.value?.resetFields();
};

</script>

<style lang="scss" scoped>
.form-dialog {
  .el-checkbox-group .el-checkbox {
    float: left;
    width: 150px;
    padding-right: 10px;
    margin: 0;
  }
}
</style>
